#!/usr/bin/env python
#coding=utf-8
from __future__ import division
import time
import datetime
import sys
from define import BASE_DIR,BLACK_LIST,route_key

sys.path.append(BASE_DIR)

from lib.abstract_cron import abstract_cron
from lib.func_ext import dateTypeInterval,str2sec,sec2str,ksort


class api_averagetime_day(abstract_cron):

    noLock = True     #是否生成脚本锁文件
    insertTable = 'sdb_statistics_api_averagetime_day'

    def __init__ (self):
        super(api_averagetime_day,self).__init__(__file__)
        self.mongo = self.objCore.mongo('mongodb_stat')
        dbConf = self.setting.get('mongodb_stat',{})
        mongoDB = dbConf.get('mongo_db_life')
        mongoBizColl = sec2str('%Y%m%d',time.time()-1*24*3600)
        self.bizColl = self.mongo[mongoDB][mongoBizColl]

        self.allTime  = {}
        self.allCount = {}
        self.argTime  = {}
        #所有api总时间
        self.allAllTime = {}
        #总api的平均时间
        self.argArgTime = {}
        #所有api总次数
        self.allAllCount = {}


    def boot(self,timestamp=[]):
        #self.preBoot()

        self.getArgData(route_key)
        self.getArgTime()

        #组合数据,插入mysql
        for api in self.allCount:
            tmpData = {}
            tmpData['api'] = api
            tmpData['sum'] = self.allCount[api]
            tmpData['alltime'] = self.allTime[api]
            tmpData['average'] = self.argTime[api]
            tmpData['calltime'] = str2sec(time.strftime('%Y-%m-%d'),'%Y-%m-%d')-1*24*3600
            tmpData['date'] = str(sec2str('%Y%m%d',time.time()-1*24*3600))
            #数据过滤
            self.filterItems(tmpData)

        tmpData = {'api':'shopex_all_api','sum':self.allAllCount,
                'alltime':self.allAllTime,'average':self.argArgTime,
                'calltime':str2sec(time.strftime('%Y-%m-%d'),'%Y-%m-%d')-1*24*3600,
                'date':str(sec2str('%Y%m%d',time.time()-1*24*3600))}
        self.filterItems(tmpData)

        #批量插入
        self.doBatchExec()
        self.sufBoot()
        print 'ok'

    def getArgData (self,route_key = {}):
        for item,api in route_key.items():
            return_data = self.bizColl.find({'route_key' : item , 'shopex_finish' : 1 })
            icount = return_data.count()
            #api 总个数
            self.allCount[api] = self.allCount.get(api,0) + icount

            self.allTime[api]  = self.allTime.get(api,0)
            for idata in return_data:
                #item = cjson.decode(item)
                tags = idata.get('tags',{})
                '''
                if len(tags) ==0:
                    start_time =0
                else:
                    start_time = idata.get('timestamp',0)
                '''
                #end_time   = self.getStartEndTime(tags)[0]
                #start_time = self.getStartEndTime(tags)[1]
                end_time,start_time = self.getStartEndTime(tags)
                self.allTime[api] = self.allTime.get(api,0) + (end_time - start_time)



    def getStartEndTime(self,tags = {}):
        tags_count = len(tags)
        startTime = 0
        endTime   = 0
        if tags_count > 0:
            for item in tags: #list
                #获取开始和结束时间
                for tmpitem in item: #dict
                    if item[tmpitem] > endTime:
                        endTime = item[tmpitem]
                    if startTime <= 0:
                        startTime = item[tmpitem]
                    elif item[tmpitem] < startTime:
                        startTime = item[tmpitem]
                    break
        return endTime,startTime

    def getArgTime(self):
        '''
            get arg time dict
        '''
        self.allAllTime = 0
        self.allAllCount = 0
        for api in self.allTime:
            if self.allCount[api] > 0:
                self.argTime [api] = round(self.allTime[api] / self.allCount[api],2)
            else:
                self.argTime [api] = 0

            self.allAllTime = self.allAllTime + self.allTime[api]
            self.allAllCount = self.allAllCount + self.allCount[api]
        if self.allAllCount > 0:
            self.argArgTime = round(self.allAllTime / self.allAllCount,2)
        else:
            self.argArgTime = 0

    def insertKeys (self):
        return ['api','sum','alltime','average','calltime','date']

if __name__ == '__main__':
    obj = api_averagetime_day()
    obj.boot()



